package com.github.tetrisgame.ui.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.github.tetrisgame.model.Block;
import com.github.tetrisgame.utils.Constants;

public class PreviewView extends View {
    private int[][] boards;
    private Bitmap mBitmap;
    private Rect mRect = new Rect();

    public PreviewView(Context context) {
        this(context,null);
    }

    public PreviewView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int mWidth = Constants.SIZE * 3;
        int mHeight = Constants.SIZE * 3;
        setMeasuredDimension(mWidth,mHeight);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        if(boards == null)return;
        for (int i = 0; i < boards.length; i++) {
            for (int j = 0; j < boards[0].length; j++) {
                if (boards[i][j] != 0){
                    mRect.left = j*Constants.SIZE;
                    mRect.top = i*Constants.SIZE;
                    mRect.right = mRect.left + Constants.SIZE;
                    mRect.bottom = mRect.top + Constants.SIZE;

                    canvas.drawBitmap(mBitmap,null,mRect,null);
                }
            }
        }

    }

    public void showBlock(Block previewBlock) {
        boards = previewBlock.getShape();
        mBitmap = BitmapFactory.decodeResource(getResources(),previewBlock.getImageResource());
        invalidate();
    }
}
